package xyf.p08.backtrack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * ClassName: P0022_GenerateParenthesis
 * Description:
 * Author: xyf
 * Date: 9/8/22 5:04 PM
 * Version: 1.0
 **/
public class P0022_GenerateParenthesis
{
    public List<String> generateParenthesis(int n)
    {
        List<String> res = new ArrayList<>();

        backtrack(n, 0, res, new StringBuilder());

        return res;
    }

    private void backtrack(int n, int index, List<String> res, StringBuilder sb)
    {
        if (index == 2 * n && check(sb.toString()))
        {
            res.add(sb.toString());
        }
        for (int i = 0; i < 2; i++)
        {
            if (i == 0)
            {
                sb.append("(");
            }
            else
            {
                sb.append(")");
            }
            backtrack(n, index + 1, res, sb);
            sb.deleteCharAt(index);
        }

    }

    private boolean check(String sb)
    {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < sb.length(); i++)
        {
            if (sb.charAt(i) == '(')
            {
                stack.push(sb.charAt(i));
            }
            else
            {
                if (stack.isEmpty())
                {
                    return false;
                }
                Character c = stack.pop();
                if (c != '(')
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        return false;
    }
}